﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CronCommon;
using System.Data;
using System.Data.SqlClient;
using DingTalk.Api;
using DingTalk.Api.Request;
using DingTalk.Api.Response;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System.Net;
using System.IO;

namespace ddPurchase
{

    class Program
    {
        static string access_token = "";
        static string access_token1 = "";
        public static string getToken()
        {

            IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
            OapiGettokenRequest req = new OapiGettokenRequest();
            req.Appkey = "dingjhuxol34h8gbmr9t";
            req.Appsecret = "qSn_nHRrU9EsHEoluHutH7oBlgDwSW2Bocm754uIBN8vFu2MOgFQ8lqWi-6Hd5eY";
            req.SetHttpMethod("GET");
            OapiGettokenResponse rsp = client.Execute(req, access_token);
            access_token = rsp.AccessToken;
            return access_token;

        }
        public static string getToken(string appKey, string appSecret)
        {

            IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
            OapiGettokenRequest req = new OapiGettokenRequest();
            req.Appkey = appKey;
            req.Appsecret = appSecret;
            req.SetHttpMethod("GET");
            OapiGettokenResponse rsp = client.Execute(req, access_token1);
            access_token1 = rsp.AccessToken;
            return access_token1;

        }




        public static void GetWorkJob()
        {
            SqlHelper.ExecuteSql("exec  P_插入打搞单  ");

        }

        public static void ddsendPurchase()
        {

            access_token = getToken();

            string sql = "select ID,工作单编号,客户编号,客户品名  from dd_打稿单采购确认 where 实例ID IS NULL ORDER BY ID";
            DataTable dataTable = SqlHelper.GetDataTable(sql);

            if (dataTable.Rows.Count > 0)
            {
                foreach (DataRow dr in dataTable.Rows)
                {


                    IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/processinstance/create");
                    OapiProcessinstanceCreateRequest req = new OapiProcessinstanceCreateRequest();
                    req.ProcessCode = "PROC-79DB1022-9E26-4BEB-9600-1435ED70B027";
                    req.OriginatorUserId = "HY005072";
                    req.DeptId = 2450944L;
                    List<OapiProcessinstanceCreateRequest.FormComponentValueVoDomain> list2 = new List<OapiProcessinstanceCreateRequest.FormComponentValueVoDomain>();
                    OapiProcessinstanceCreateRequest.FormComponentValueVoDomain obj3 = new OapiProcessinstanceCreateRequest.FormComponentValueVoDomain();
                    list2.Add(obj3);
                    obj3.Name = "工作单编号";
                    obj3.Value = dr["工作单编号"].ToString();


                    OapiProcessinstanceCreateRequest.FormComponentValueVoDomain obj4 = new OapiProcessinstanceCreateRequest.FormComponentValueVoDomain();
                    list2.Add(obj4);
                    obj4.Name = "需采购物料类型";
                    obj4.Value = "[\"辅料\",\"原料\"]";

                    /*

                    OapiProcessinstanceCreateRequest.FormComponentValueVoDomain obj5 = new OapiProcessinstanceCreateRequest.FormComponentValueVoDomain();
                    list2.Add(obj5);
                    obj5.Name = "原料预计回厂日期";
                    obj5.Value = "2022-09-30";
                    obj5.ExtValue = "原料预计回厂日期";



                    OapiProcessinstanceCreateRequest.FormComponentValueVoDomain obj6 = new OapiProcessinstanceCreateRequest.FormComponentValueVoDomain();
                    list2.Add(obj6);
                    obj6.Name = "辅料预计回厂日期";
                    obj6.Value = "2022-09-30";
                    obj6.ExtValue = "原料预计回厂日期";
                    */
                    OapiProcessinstanceCreateRequest.FormComponentValueVoDomain obj7 = new OapiProcessinstanceCreateRequest.FormComponentValueVoDomain();
                    list2.Add(obj7);
                    obj7.Name = "客户品名";
                    obj7.Value = dr["客户品名"].ToString();

                    OapiProcessinstanceCreateRequest.FormComponentValueVoDomain obj8 = new OapiProcessinstanceCreateRequest.FormComponentValueVoDomain();
                    list2.Add(obj8);
                    obj8.Name = "客户编号";
                    obj8.Value = dr["客户编号"].ToString();


                    req.FormComponentValues_ = list2;
                    OapiProcessinstanceCreateResponse rsp = client.Execute(req, access_token);
                    string sqlstr = $"update dd_打稿单采购确认 set  实例ID='" + rsp.ProcessInstanceId + "'  WHERE  工作单编号='" + dr["工作单编号"].ToString() + "'";
                    SqlHelper.ExecuteSql(sqlstr);

                    Log.Writter($"完成后返回信息:{rsp.Body}");

                }

            }
        }

        public static void ddWriteBack()
        {

            string sql = "select  ID, 实例ID,工作单编号 from dd_打稿单采购确认 where   实例ID>'''' AND 审批人员1 is null and   ISNULL(审批状态,'NEW') IN ('NEW','RUNNING')  ORDER BY ID";
            DataTable dataTable = SqlHelper.GetDataTable(sql);
            if (dataTable.Rows.Count > 0)
            {
                access_token = getToken();

                IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/processinstance/get");
                OapiProcessinstanceGetRequest req = new OapiProcessinstanceGetRequest();

                foreach (DataRow dr in dataTable.Rows)
                {

                    req.ProcessInstanceId = dr["实例ID"].ToString();
                    OapiProcessinstanceGetResponse rsp = client.Execute(req, access_token);
                    ParseSignID(rsp.Body, dr["ID"].ToString());
                }

            }
        }

        public static void ParseSignID(string Body, string ID)
        {

            string sql;
            StringBuilder stringBuilder = new StringBuilder();
            string jsonText = Body;
            JObject jsonObj = JObject.Parse(jsonText);
            JObject jsonObj1 = (JObject)jsonObj["process_instance"];
            string create_time = jsonObj1["create_time"].ToString();  //创建时间
                                                                      //  string originator_userid = jsonObj1["originator_userid"].ToString();//发起人
                                                                      //  string finish_time = jsonObj1["finish_time"].ToString();//结束时间
            string result = jsonObj1["result"].ToString();//审批结果

            /*     审批状态：NEW：新创建 RUNNING：审批中 TERMINATED：被终止 COMPLETED：完成  CANCELED：取消*/
            string status = jsonObj1["status"].ToString();//审批状态
            int j = 1;
            foreach (var aa in jsonObj["process_instance"]["operation_records"])
            {
                if (!aa["operation_result"].ToString().Equals("NONE"))
                {
                    stringBuilder.AppendLine("审批结果" + j.ToString() + "='" + aa["operation_result"].ToString() + "',审批人员" + j.ToString() + " = '" + aa["userid"].ToString()
                        + "',审批时间" + j.ToString() + " = '" + aa["date"].ToString() + "',");
                    if (aa["remark"] != null)
                    {
                        stringBuilder.AppendLine("  审批意见" + j.ToString() + "='" + aa["remark"].ToString() + "',");
                    }

                    j++;
                }

            }


            //取得表单内容
            JArray formArry = (JArray)JsonConvert.DeserializeObject(jsonObj1["form_component_values"].ToString());
            // stringBuilder.Clear();
            foreach (var A in formArry.Children())
            {

                if (!A["name"].ToString().Equals("工作单编号"))
                {
                    if (!A["value"].ToString().Equals("null"))
                        stringBuilder.AppendLine(A["name"] + "= '" + A["value"].ToString().Replace("'","''") + "',");
                }

            }


            sql = "  update dd_打稿单采购确认 set   " + stringBuilder.ToString() + " 发起时间='" + create_time + "', 审批结果='" + result + "',审批状态='" + status + "' ,记录回写时间=GETDATE()  WHERE ID=" + ID;
            //  textBox1.Text = sql;
           // Log.Writter(sql);
            SqlHelper.ExecuteSql(sql);


        }

        public static void ddSendMsg_OA()
        {
            /*
            long AgentId = 1900554480L;
            string AppKey = "dingxlfhzy83wtjxfiim";
            string AppSecret = "ScFiZ4HSUpyJ29nD7GmrqQZwK7GeWUSJ1Ahpik4CZpYG7KAkdopfz7EC5vvH37PK";
            access_token1 = getToken(AppKey, AppSecret);
            */
            string sql = "exec   P_钉钉发送工序超时通知 ";
            StringBuilder stringBuilder = new StringBuilder();
            DataTable dataTable = SqlHelper.GetDataTable(sql);
            if (dataTable.Rows.Count > 0)
            {
                long AgentId = 1975755843L;
                string AppKey = "ding3io0zifhwpaaqxzq";
                string AppSecret = "jxRwaiaAmMpHfFPewwIGAzMAwswgxkx3WcwO0f0GHTWz3lRptYAOxrsLcom9xXLD";
                access_token1 = getToken(AppKey, AppSecret);


                foreach (DataRow dr in dataTable.Rows)
                {
                    string msgtext = "前工序【" + dr["前工序"] + "】已经生产完成超过" + dr["工序时长"].ToString() + "小时,当前工序【" + dr["工序"] + "】 还未生产 ，请注意跟进生产是否正常。\n如本工序不是您管辖区域生产，请忽略此信息   \n提醒时间:" + DateTime.Now.ToString();
                    string url = "http://116.6.133.110:20001/mes/S_WorkJOBView/S_WorkJobViewindex.aspx?workJobNo=" + dr["工作单编号"];
                    string result = ddsendworkinfo(AgentId, access_token1, dr["接收人"].ToString(), msgtext, $"工作单编号：{dr["工作单编号"]}", "打搞工序超时提醒", url, url);
                    if (result.Equals("ok") == true)
                    {
                        stringBuilder.AppendLine($" update 工作单工序顺序表 set 发送通知否='Y',发送通知时间=GETDATE(),接收人='{dr["接收人"].ToString()}'   WHERE 工作单编号='{dr["工作单编号"]}' and 排序次序= '{dr["需要发送通知次序"].ToString()}' ");
                    }


                }
                if (string.IsNullOrEmpty(stringBuilder.ToString()) == false)
                {
                    SqlHelper.ExecuteSql(stringBuilder.ToString());
                }

            }
        }

        public static string ddsendworkinfo(long AgentId, string AccessToken, string UseridList, string msgtext, string Title, string headTitle, string pcUrl, string MessageUrl)
        {
            IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2");
            OapiMessageCorpconversationAsyncsendV2Request req = new OapiMessageCorpconversationAsyncsendV2Request();
            req.AgentId = AgentId;
            req.UseridList = UseridList;
            OapiMessageCorpconversationAsyncsendV2Request.MsgDomain obj1 = new OapiMessageCorpconversationAsyncsendV2Request.MsgDomain();
            obj1.Msgtype = "oa";
            OapiMessageCorpconversationAsyncsendV2Request.TextDomain obj2 = new OapiMessageCorpconversationAsyncsendV2Request.TextDomain();
            obj2.Content = msgtext;
            obj1.Text = obj2;
            OapiMessageCorpconversationAsyncsendV2Request.OADomain obj3 = new OapiMessageCorpconversationAsyncsendV2Request.OADomain();
            OapiMessageCorpconversationAsyncsendV2Request.BodyDomain obj4 = new OapiMessageCorpconversationAsyncsendV2Request.BodyDomain();
            obj4.Content = msgtext;
            obj4.Title = Title;
            obj3.Body = obj4;
            OapiMessageCorpconversationAsyncsendV2Request.HeadDomain obj5 = new OapiMessageCorpconversationAsyncsendV2Request.HeadDomain();
            obj5.Text = headTitle;
            obj3.Head = obj5;
            obj3.PcMessageUrl = pcUrl;
            obj3.MessageUrl = MessageUrl;
            obj1.Oa = obj3;
            OapiMessageCorpconversationAsyncsendV2Request.ActionCardDomain obj6 = new OapiMessageCorpconversationAsyncsendV2Request.ActionCardDomain();
            List<OapiMessageCorpconversationAsyncsendV2Request.BtnJsonListDomain> list8 = new List<OapiMessageCorpconversationAsyncsendV2Request.BtnJsonListDomain>();
            OapiMessageCorpconversationAsyncsendV2Request.BtnJsonListDomain obj9 = new OapiMessageCorpconversationAsyncsendV2Request.BtnJsonListDomain();
            list8.Add(obj9);
            obj9.Title = Title;
            obj6.BtnJsonList = list8;
            obj1.ActionCard = obj6;
            req.Msg_ = obj1;
            OapiMessageCorpconversationAsyncsendV2Response rsp = client.Execute(req, AccessToken);
            Console.WriteLine(rsp.Errmsg);
            return rsp.Errmsg;



        }

        static void Main(string[] args)
        {

            ddSendMsg_OA();//打稿下道工序未生产提醒
            GetWorkJob();
            ddsendPurchase();
            ddWriteBack();
            Environment.Exit(0);
        }
    }
}
